#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
MES数据集成模块
用于将MES数据接收服务收集的数据与仪表盘系统集成
"""

import os
import json
import sqlite3
import time
import sys
from datetime import datetime, timedelta

# 设置标准输出编码
sys.stdout.reconfigure(encoding='utf-8')
sys.stderr.reconfigure(encoding='utf-8')

# MES数据库路径
MES_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'mes_data.db')

# 仪表盘数据库路径
DASHBOARD_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'backend', 'instance', 'dashboard.db')

def get_mes_db_connection():
    """获取MES数据库连接"""
    conn = sqlite3.connect(MES_DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def get_dashboard_db_connection():
    """获取仪表盘数据库连接"""
    conn = sqlite3.connect(DASHBOARD_DB_PATH)
    conn.row_factory = sqlite3.Row
    return conn

def get_recent_product_data(hours=24):
    """获取最近一段时间的产品数据"""
    conn = get_mes_db_connection()
    cursor = conn.cursor()

    # 计算时间范围
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours)

    # 查询数据
    cursor.execute('''
    SELECT * FROM product_data
    WHERE timestamp >= ? AND timestamp <= ?
    ORDER BY timestamp ASC
    ''', (start_time.isoformat(), end_time.isoformat()))

    data = [dict(row) for row in cursor.fetchall()]
    conn.close()

    return data

def get_device_status():
    """获取设备状态数据"""
    conn = get_mes_db_connection()
    cursor = conn.cursor()

    cursor.execute('SELECT * FROM device_status')
    data = [dict(row) for row in cursor.fetchall()]

    conn.close()
    return data

def update_dashboard_data():
    """更新仪表盘数据"""
    try:
        # 获取MES数据
        product_data = get_recent_product_data()
        device_status = get_device_status()

        # 转换为仪表盘需要的格式
        dashboard_data = []

        for product in product_data:
            # 查找对应的设备状态
            device = next((d for d in device_status if d['device_id'] == product['device_id']), None)

            if device:
                # 创建仪表盘数据记录
                record = {
                    'timestamp': product['timestamp'],
                    'equipmentName': product['device_id'],
                    'totalMeters': product['length'],
                    'averageSpeed': product['speed'],
                    'runningTime': 300,  # 假设每条记录运行5分钟
                    'alarmTime': 0,  # 默认无报警
                    'operator': device.get('operator_id', '未知'),
                    'shiftType': device.get('shift_type', '未知'),
                    'paperBreakCount': 0,
                    'otherAlarmCount': 0
                }

                # 如果设备状态为故障，添加报警时间
                if device.get('status') == 'fault':
                    record['alarmTime'] = 300  # 假设报警持续5分钟
                    record['otherAlarmCount'] = 1

                dashboard_data.append(record)

        # 保存到仪表盘数据文件
        output_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'backend', 'test_data', 'mes_integration_data.json')

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(dashboard_data, f, ensure_ascii=False, indent=2)

        print(f'已更新仪表盘数据，共 {len(dashboard_data)} 条记录')
        return True

    except Exception as e:
        print(f'更新仪表盘数据时出错: {str(e)}')
        return False

def update_realtime_status():
    """更新实时状态数据"""
    try:
        # 获取设备状态
        device_status = get_device_status()

        # 转换为仪表盘需要的格式
        realtime_status = []

        for device in device_status:
            # 获取设备最新的产品数据
            conn = get_mes_db_connection()
            cursor = conn.cursor()

            cursor.execute('''
            SELECT * FROM product_data
            WHERE device_id = ?
            ORDER BY timestamp DESC
            LIMIT 1
            ''', (device['device_id'],))

            latest_product = cursor.fetchone()
            conn.close()

            # 创建实时状态记录
            status = {
                'equipmentName': device['device_id'],
                'status': '在线' if device['status'] == 'online' else '离线',
                'operator': device.get('operator_id', None),
                'clockInTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'currentMeters': latest_product['length'] if latest_product else 0,
                'averageSpeed': latest_product['speed'] if latest_product else 0,
                'runningStatus': '运行中' if device['status'] == 'online' else '停止中',
                'alarmStatus': '报警中' if device['status'] == 'fault' else '正常',
                'alarmType': '设备故障' if device['status'] == 'fault' else None,
                'shiftType': device.get('shift_type', None),
                'updateTime': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }

            realtime_status.append(status)

        # 保存到仪表盘数据文件
        output_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'backend', 'test_data', 'realtime_status.json')

        with open(output_file, 'w', encoding='utf-8') as f:
            json.dump(realtime_status, f, ensure_ascii=False, indent=2)

        print(f'已更新实时状态数据，共 {len(realtime_status)} 台设备')
        return True

    except Exception as e:
        print(f'更新实时状态数据时出错: {str(e)}')
        return False

def run_integration_service():
    """运行集成服务"""
    print('启动MES数据集成服务...')

    try:
        while True:
            # 更新仪表盘数据
            update_dashboard_data()

            # 更新实时状态数据
            update_realtime_status()

            # 等待一段时间再更新
            print(f'等待30秒后再次更新...')
            time.sleep(30)

    except KeyboardInterrupt:
        print('集成服务已停止')

if __name__ == '__main__':
    run_integration_service()
